//
//  ZDPictureView.m
//  OCSinaWeiBo
//
//  Created by Apple on 15/11/2.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDPictureView.h"
#import "ZDStatus.h"
#import <Masonry/Masonry.h>
#import "UIImageView+Extension.h"
#import <SDWebImage/SDWebImageManager.h>
#import "ZDPhotoBrowserModel.h"

NSString *const ZDPictureViewCellDidSelectNotification = @"ZDPictureViewCellDidSelectNotification";
NSString *const ZDPictureViewCellSelectedIndexKey = @"ZDPictureViewCellSelectedIndexKey";
NSString *const ZDPictureViewCellPhotoBrowserModelKey = @"ZDPictureViewCellPhotoBrowserModelKey";


static NSString *collectionCellIdentifier = @"ZDPictureViewCell";

@interface ZDPictureView () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionViewFlowLayout *layout;

@end

@implementation ZDPictureView

- (instancetype)init
{
    [self prepareUI];
    
    return [super initWithFrame:CGRectZero collectionViewLayout:self.layout];
}


//准备UI
- (void)prepareUI
{
    self.backgroundColor = [UIColor clearColor];
    
    //指定数据源
    self.dataSource = self;
    //指定代理
    self.delegate = self;
    
    //注册cell
    [self registerClass:[ZDPictureViewCell class] forCellWithReuseIdentifier:collectionCellIdentifier];

}

- (void)setStatus:(ZDStatus *)status
{
    _status = status;
    
    [self reloadData];
}


/**
 *  根据配图数量 动态计算collectionView的size
 */
- (CGSize)calculatCollectionViewSize
{
    //设置默认的itemSize
    _layout.itemSize = CGSizeMake(90, 90);
    _layout.minimumLineSpacing = 0;
    _layout.minimumInteritemSpacing = 0;
    
    NSInteger count = _status.pictureURLs.count;
    
    if (count == 0)
    {
        return CGSizeZero;
    }
    
    if (count == 1)
    {
        CGSize itemSize = CGSizeMake(150, 120);
        
        NSURL *url = _status.pictureURLs.firstObject;
        //将url转换成字符串
        NSString *urlString = [url absoluteString];
        //从缓存加载下载好的图片
        UIImage *image = [[SDWebImageManager sharedManager].imageCache imageFromDiskCacheForKey:urlString];
        
        //有图片的话 执行(可能缓存图片失败)
        if (image) {
            
            itemSize = image.size;
        }
        
        //防止图片宽度太小 无法点击
        if (itemSize.width < 40)
        {
            itemSize.width = 40;
        }
        
        _layout.itemSize = itemSize;
        
        return itemSize;
    }
    
    CGFloat padding = 10;
    
    _layout.minimumInteritemSpacing = padding;
    _layout.minimumLineSpacing = padding;
    
    if (count == 4)   // 2 x 2 布局
    {
        CGFloat width = 2 * 90 + padding;
        
        return CGSizeMake(width, width);
    }
    
    //剩下的都按照 3 x 3 布局
    NSInteger colown = 3;
    CGFloat row = (count + colown - 1) / colown;
    
    CGFloat width = colown * 90 + (colown-1) * padding;
    CGFloat height = row * 90 + (row - 1) * padding;
    
    return CGSizeMake(width, height);
}


#pragma mark - 数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.status.pictureURLs.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZDPictureViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellIdentifier forIndexPath:indexPath];
    
//    cell.backgroundColor = [UIColor colorWithHue:arc4random() % 256 / 256.0 saturation:arc4random() % 128 / 256.0 + 0.5 brightness:arc4random() % 128 / 256.0 + 0.5 alpha:1.0];
    
    cell.imageURL = self.status.pictureURLs[indexPath.item];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *models = [NSMutableArray array];
    
    NSUInteger count = self.status.pictureURLs.count;
    
    for (NSUInteger index = 0; index < count; index++)
    {
        NSIndexPath *indexP = [NSIndexPath indexPathForItem:index inSection:0];
        
        //根据indexP获取cell
        ZDPictureViewCell *cell = (ZDPictureViewCell *)[collectionView cellForItemAtIndexPath:indexP];
        
        ZDPhotoBrowserModel *model = [ZDPhotoBrowserModel photoBrowserModelWithURL:self.status.pictureURLs[index] andImageView:cell.imageView];
        
        //添加到模型数组中
        [models addObject:model];
    }
    
    //通知控制器 呼出图片查看器
    NSDictionary *userInfo = @{
                               ZDPictureViewCellSelectedIndexKey: @(indexPath.item),
                               ZDPictureViewCellPhotoBrowserModelKey: models
                               };
    
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:ZDPictureViewCellDidSelectNotification object:self userInfo:userInfo];
}


#pragma mark 懒加载
- (UICollectionViewFlowLayout *)layout
{
    if (!_layout)
    {
        _layout = [[UICollectionViewFlowLayout alloc] init];
    }
    
    return _layout;
}

@end



/**
 *  自定义collectionCell
 */
@implementation ZDPictureViewCell
{
    UIImageView *_gifView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self prepareUI];
    }
    return self;
}

- (void)prepareUI
{
    
    //添加控件
    [self.contentView addSubview: self.imageView];
    [self.contentView addSubview:self.gifView];
    
    //添加约束
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.bottom.right.mas_equalTo(self.contentView);
    }];
    
    [_gifView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.right.mas_equalTo(self.contentView);
    }];
}


- (void)setImageURL:(NSURL *)imageURL
{
    _imageURL = imageURL;
    
    [_imageView zd_setImageWithURL:imageURL];
    
    BOOL isGif = [[[[imageURL absoluteString] pathExtension] lowercaseString] isEqualToString:@"gif"];
    
    _gifView.hidden = !isGif;
}


#pragma mark 懒加载
- (UIImageView *)imageView
{
    if (!_imageView)
    {
        _imageView = [[UIImageView alloc] init];
        
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        
        _imageView.clipsToBounds = YES;
    }
    
    return _imageView;
}

- (UIImageView *)gifView
{
    if (!_gifView)
    {
        _gifView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"timeline_image_gif"]];
    }
    
    return _gifView;
}

@end
